/*
 * @Author: yangni 920556271@qq.com
 * @Date: 2024-03-07 08:55:59
 * @LastEditors: yangni 920556271@qq.com
 * @LastEditTime: 2024-05-13 09:34:49
 * @FilePath: /yt-devops/lib/pages/devices/add_charge_end/add_charge_end_controller.dart
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:native_dart_package/native_dart_package.dart';
import 'package:reactive_forms/reactive_forms.dart';
import 'package:sprintf/sprintf.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/model/device_obj/product_config_model.dart';
import 'package:yt_devops/pages/devices/device_controll/page_component/charge_terminal/charge_termimal_list/charge_termimal_list_model.dart';
import 'package:yt_devops/pages/devices/device_list/device_list_model.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/utils/brn_row1_delegate.dart';
import 'package:yt_devops/utils/func_utils.dart';

class AddChargeTerminalController extends GetxController {
  DeviceServices services = Get.find<DeviceServices>();

  ///
  int? deviceId;

  ///
  int? chargingId;
  late FormGroup form;

  late FormGroup Function() buildForm = () => fb.group(<String, Object>{
        'product': FormControl<ProductDetailModel>(value: ProductDetailModel()),
        'name': FormControl<String>(value: ''),
        'sn': FormControl<String>(validators: [Validators.required], value: ''),
      });

  String title = '';

  List<ProductDetailModel> productList = [];

  bool get isAdd => chargingId != null;

  @override
  void onInit() {
    if (Get.arguments['termimal'] != null) {
      var data = Get.arguments['termimal'];

      if (data is ChargeTerminalModel) {
        deviceId = data.id;
        buildForm = initData(data);
      }

      title = sprintf(
          ResKey.commonEditSentence.tr, [ResKey.devicechargingTerminal.tr]);
    } else {
      chargingId = Get.arguments['chargingId'];
      title = sprintf(
          ResKey.commonCreateSentence.tr, [ResKey.devicechargingTerminal.tr]);
    }
    super.onInit();
  }

  @override
  void onReady() {}

  @override
  void onClose() {}

  FormGroup Function() initData(ChargeTerminalModel data) {
    return () => fb.group(<String, Object>{
          'product': FormControl<ProductDetailModel>(
            disabled: true,
            value: ProductDetailModel(
                productType: data.productType,
                name: data.deviceName,
                id: data.id),
          ),
          'name': FormControl<String>(value: data.deviceName),
          'sn': FormControl<String>(
              disabled: true,
              validators: [Validators.required],
              value: data.sn),
        });
  }

  save(FormGroup form) {
    if (isAdd) {
      add(form);
    } else {
      updateTerm(form);
    }
  }

  add(FormGroup form) => Configs.httpClient.requestWithLoading(() async {
        await services.addChargeTerm({
          'chargingId': chargingId,
          'productId': (form.control('product').value as ProductDetailModel).id,
          'name': form.control('name').value,
          'sn': form.control('sn').value,
        });
        dismissLoading();
        await FuncUtils.requestTipsDislog(
            Get.context, ResKey.createdSuccessfully.tr, true,
            duration: const Duration(seconds: 2));
        Get.back(result: true);
      });

  updateTerm(FormGroup form) => Configs.httpClient.requestWithLoading(() async {
        await services.updateChargeTerm({
          'deviceId': deviceId,
          'name': form.control('name').value,
        });
        dismissLoading();
        await FuncUtils.requestTipsDislog(
            Get.context, ResKey.modifiedSuccessfully.tr, true,
            duration: const Duration(seconds: 2));
        Get.back(result: true);
      });

  toSelectProduct(BuildContext context) =>
      Configs.httpClient.requestWithLoading(() async {
        if (productList.isEmpty) {
          var data = await services.getProductModelList({'productTypeId': 547});
          productList = data
              .map<ProductDetailModel>((e) => ProductDetailModel(
                    id: e['id'],
                    name: e['model'],
                  ))
              .toList();
        }

        var list = productList.map<String>((e) => e.name ?? '').toList();

        BrnMultiDataPicker(
          context: Get.context!,
          delegate: Brn1RowDelegate(list),
          confirmClick: (selectedIndexList) {
            form.resetState({
              'product': ControlState<ProductDetailModel>(
                  value: productList[selectedIndexList[0]]),
            });
          },
        ).show();
      });
}
